//
//  NSObject+HACForwarding.m
//  HACShield
//
//  Created by Chengjie on 2019/5/25.
//

#import "NSObject+HACForwarding.h"
#import "NSObject+HACSwizzling.h"
#import "HACCrashSavior.h"

@implementation NSObject (HACForwarding)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        hac_swizzleInstanceMethod(hac_getClass(@"NSO", @"bject"), @selector(forwardingTargetForSelector:), @selector(hac_instanceForwardingTargetForSelector:));
        hac_swizzleInstanceMethod(hac_getMetaClass(@"NSO", @"bject"), @selector(forwardingTargetForSelector:), @selector(hac_classForwardingTargetForSelector:));
    });
}

- (id)hac_instanceForwardingTargetForSelector:(SEL)aSelector {
   if ([self isKindOfClass:[NSString class]] && [NSNumber instancesRespondToSelector:aSelector]) {
        NSString *str = (NSString *)self;
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        NSNumber *number = [formatter numberFromString:str];
        return number;
    } else if ([self isKindOfClass:[NSNumber class]] && [NSString instancesRespondToSelector:aSelector]) {
        NSNumber *number = (NSNumber *)self;
        NSString *str = [number stringValue];
        return str;
    } else {
        BOOL aBool = [self respondsToSelector:aSelector];
        NSMethodSignature *signatrue = [self methodSignatureForSelector:aSelector];
        if (aBool || signatrue) {
            return [self hac_instanceForwardingTargetForSelector:aSelector];
        } else {
            HACCrashSavior *savior = [HACCrashSavior new];
            [savior hac_addInstanceSaviorSel:aSelector];
            return savior;
        }
    }
}

+ (id)hac_classForwardingTargetForSelector:(SEL)aSelector {
    BOOL aBool = [self respondsToSelector:aSelector];
    NSMethodSignature *signatrue = [self methodSignatureForSelector:aSelector];
    if (aBool || signatrue) {
        return [self hac_instanceForwardingTargetForSelector:aSelector];
    } else {
        [HACCrashSavior hac_addClassSaviorSel:aSelector];
        return [HACCrashSavior class];
    }
}

@end
